package io.github.fb513.api.controller;

import com.ecwid.consul.v1.health.model.Check;
import com.ecwid.consul.v1.health.model.HealthService;
import io.github.fb513.api.config.Login;
import io.github.fb513.api.facade.MessageFacade;
import io.github.fb513.api.model.CommonResp;
import io.github.fb513.api.model.response.AddrResp;
import io.github.fb513.api.model.response.OfflineMsgResp;
import io.github.fb513.api.util.RespUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.consul.discovery.ConsulServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author fengbo
 * @since 2023-12-27
 */
@RestController
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private MessageFacade messageFacade;

    @GetMapping("/active/service/info")
    public CommonResp<AddrResp> getActiveServiceList() {
        List<ServiceInstance> instances = discoveryClient.getInstances("im-transport");
        List<AddrResp> addrRespList = new ArrayList<>(instances.size());
        for (ServiceInstance instance : instances) {
            HealthService healthService = ((ConsulServiceInstance) instance).getHealthService();
            List<Check> checks = healthService.getChecks();
            boolean isHealthy = true;
            for (Check check : checks) {
                if (check.getCheckId().endsWith(instance.getInstanceId()) && !Check.CheckStatus.PASSING.equals(check.getStatus())) {
                    isHealthy = false;
                    break;
                }
            }
            if (isHealthy) {
                AddrResp addrResp = new AddrResp();
                addrResp.setHost(instance.getHost());
                addrResp.setPort(instance.getPort());
                addrRespList.add(addrResp);
            }
        }
        return RespUtils.success(addrRespList.get(0));
    }

    @GetMapping("/offline/list")
    public CommonResp<List<OfflineMsgResp>> getOfflineMessageList(@Login Long userId,
                                                                  @RequestParam Long sessionUserId,
                                                                  @RequestParam(required = false) Long maxMsgId) {
        return RespUtils.success(messageFacade.getOfflineMessageList(userId, sessionUserId, maxMsgId));
    }

}
